<!-- 
  vxe-table 表格组件库
    docs: https://vxetable.cn/#/table/grid/fullEdit
 -->

<template>
  <div class="table-layout">
    <div class="table-header">
      <el-select
        v-model="currentName"
        placeholder="请选择"
        @change="getTableData"
      >
        <el-option
          v-for="item in collectionList"
          :key="item"
          :label="item"
          :value="item"
        >
        </el-option>
      </el-select>

      <div class="alick-handle-btns">
        <el-button
          class="handle-btn"
          type="success"
          size="small"
          @click="removeWeight"
        >
          去除无用数据
        </el-button>
        <el-button
          class="handle-btn"
          type="success"
          size="small"
          @click="removeWeight"
        >
          去除损坏数据
        </el-button>
        <el-button
          class="handle-btn"
          type="success"
          size="small"
          @click="removeWeight"
        >
          去除重复数据
        </el-button>
        <el-button
          class="handle-btn"
          type="success"
          size="small"
          @click="removeAll"
        >
          一键删除
        </el-button>
      </div>
    </div>

    <div id="table-container">
      <template v-if="tableData && tableData.length">
        <vxe-table
          border="none"
          show-overflow="tooltip"
          ref="xTable"
          align="center"
          keep-source
          :row-config="{ isHover: true }"
          :sort-config="{ trigger: 'cell' }"
          :edit-config="{ trigger: 'dblclick', mode: 'cell' }"
          height="100%"
          :data="tableData"
        >
          <vxe-column
            v-for="(key, index) in filteredKeys"
            :field="key"
            :title="key"
            :edit-render="{ name: 'input' }"
            :key="index"
          >
            <template #edit="{ row }">
              <vxe-input
                v-model="row[key]"
                type="text"
                :placeholder="`请输入${key}`"
              ></vxe-input>
            </template>
          </vxe-column>

          <vxe-column title="操作" fixed="right" width="200">
            <template #default="{ row }">
              <vxe-button
                type="text"
                status="success"
                @click.native="saveRowEvent(row)"
                >保存</vxe-button
              >
              <vxe-button
                type="text"
                status="primary"
                @click="cancelRowEvent(row)"
                >取消</vxe-button
              >
              <el-popconfirm
                title="您确定要删除吗？"
                @onConfirm="removeEvent(row)"
              >
                <vxe-button slot="reference" type="text" status="danger">
                  删除
                </vxe-button>
              </el-popconfirm>
            </template>
          </vxe-column>
        </vxe-table>
      </template>
    </div>
  </div>
</template>

<script>
import {
  getDocument,
  updateDocument,
  delDocument,
  removeWeightDocument,
  removeAllDocument,
  getCollectionByProject,
} from "@/api/dataMart.js";

export default {
  data() {
    return {
      collectionList: [],
      currentName: "",
      tableData: [],
    };
  },
  computed: {
    filteredKeys() {
      // 确保 tableData 不为空并有数据
      if (this.tableData.length && this.tableData[0]) {
        return Object.keys(this.tableData[0]).filter(
          (key) => key !== "_id" && key !== "_X_ROW_KEY"
        );
      }
      return [];
    },
  },
  async mounted() {
    this.getData();

    // this.$nextTick(() => {
    //   const $table = this.$refs.xTable
    //   // this.mockList().then(data => {
    //   //   if ($table) {
    //   //     console.log(data, "detailData");
    //   //     $table.loadData(this.detailData)
    //   //   }
    //   // })
    // })
  },

  destroyed() {},
  methods: {
    async getData() {
      let res = await getCollectionByProject(this.$route.query.id);
      this.collectionList = res.data.map((item) => item.name);

      this.currentName = this.collectionList[0];

      if (this.currentName) {
        this.getTableData();
      }
    },

    async getTableData() {
      let res = await getDocument({ collection: this.currentName });
      // 不显示projectId
      res.data.map((item) => {
        delete item.projectId;
      });
      this.tableData = res.data;
    },

    async removeWeight() {
      const response = await removeWeightDocument({
        collection: this.currentName,
        project_id: this.$route.query.id,
      });

      if (response.code === 200) {
        this.getTableData();

        setTimeout(() => {
          this.$message({ message: "去重完成", type: "success" });
        }, 300);
      } else {
        this.$message({
          message: response.message || "去重失败",
          type: "error",
        });
      }
    },

    async removeAll() {
      const response = await removeAllDocument({
        collectionName: this.currentName,
        projectId: this.$route.query.id,
      });

      if (response.code === 200) {
        this.getTableData();

        setTimeout(() => {
          this.$message({ message: "删除完成", type: "success" });
        }, 300);
      } else {
        this.$message({
          message: response.message || "删除失败",
          type: "error",
        });
      }
    },

    editRowEvent(row) {
      const $table = this.$refs.xTable;
      $table.setEditRow(row);
    },
    // async saveRowEvent(row) {
    //   const response = await updateDocument({
    //     collection: this.currentName,
    //     document: row,
    //   });
    //   if (response.code === 200) {
    //     this.getTableData();

    //     const $table = this.$refs.xTable;
    //     await $table.clearActived()
    //     $table.clearActived().then(() => {
    //       setTimeout(() => {
    //         this.$message({ message: "保存成功", type: "success" });
    //       }, 300);
    //     });
    //   } else {
    //     this.$message({ message: response.message, type: "error" });
    //   }
    // },
    // async saveRowEvent(row) {
    //   console.log("1111");
    //   const $table = this.$refs.xTable;

    //   try {
    //     // 执行保存操作
    //     const response = await updateDocument({
    //       collection: this.currentName,
    //       document: row,
    //     });
    //     console.log("response", response);
    //     if (response.code === 200) {
    //       await this.getTableData();
    //       setTimeout(() => $table.clearActived(), 50);
    //       // 清除该行的编辑状态，确保不会自动激活第一个单元格
    //       // await

    //       // 添加成功提示
    //       this.$message({ message: "保存成功", type: "success" });
    //     } else {
    //       this.$message({ message: response.message, type: "error" });
    //     }
    //   } catch (error) {
    //     this.$message({ message: "保存失败", type: "error" });
    //   }
    // },

    // cancelRowEvent(row) {
    //   console.log("row", row);
    //   const $table = this.$refs.xTable;
    //   $table.clearActived().then(() => {
    //     // 还原行数据
    //     $table.revertData(row);
    //   });
    // },
    async saveRowEvent(row) {
      try {
        const response = await updateDocument({
          collection: this.currentName,
          document: row,
        });

        if (response.code === 200) {
          await this.getTableData();

          // 确保清除当前单元格的编辑状态
          await this.$refs.xTable.clearActived();
          this.$message({ message: "保存成功", type: "success" });
        } else {
          this.$message({ message: response.message, type: "error" });
        }
      } catch (error) {
        this.$message({ message: "保存失败", type: "error" });
      }
    },

    cancelRowEvent(row) {
      // 清除编辑状态，并还原数据
      this.$refs.xTable.clearActived().then(() => {
        this.$refs.xTable.revertData(row);
      });
    },
    // async removeEvent(row) {
    //   const response = await delDocument({
    //     collectionName: this.currentName,
    //     id: row._id,
    //   });
    //   if (response.code === 200) {
    //     this.getTableData();

    //     const $table = this.$refs.xTable;
    //     $table.removeCheckboxRow();
    //     setTimeout(() => {
    //       this.$message({ message: "删除成功", type: "success" });
    //     }, 300);
    //   } else {
    //     this.$message({ message: response.message, type: "error" });
    //   }
    // },
    async removeEvent(row) {
      const response = await delDocument({
        collectionName: this.currentName,
        id: row._id,
      });
      if (response.code === 200) {
        // 更新表格数据
        this.getTableData();
        this.$message({ message: "删除成功", type: "success" });
      } else {
        this.$message({ message: response.message, type: "error" });
      }
    },
  },
};
</script>
<style lang="less" scoped>
@import "~@/assets/css/table.less";
/deep/ .el-select-dropdown {
  overflow-y: auto;
}
/deep/ .el-input--suffix .el-input__inner {
  height: 28px;
  line-height: 28px;
  background-color: #1e2835;
  border: #6a798d;
  color: #a4adcd;
}
</style>
